//import router from "~/router"  修改动态路由器前的引入方法
import { router,addRoutes } from "~/router"
import { getToken } from "~/composables/auth"
import { toast,showFullLoading,hideFullLoading } from '~/composables/util'
import store from "./store"

//全局前置守卫
let hasGetInfo = false
router.beforeEach(async(to,from,next) => {
  // ...
  showFullLoading()
  const token = getToken()
  //没有登陆，强制跳转回登录页
  if(!token && to.path =="/admin" ){
    toast("请先登录","error")
    return next({path:"/admin/login"})
  }
  //防止重复登陆
  if(token && to.path =="/admin/login" ){
    toast("请勿重复登录","error")
    return next({path:from.path ? from.path : "/admin"})
  }

  //如果用户登录，自动获取用户信息，并存储vuex中
  let hasNewRoutes = false
  if(token && !hasGetInfo){
    const res = await store.dispatch("getinfo")
    let { menu } = res.data
    hasGetInfo = true
    //console.log(menu);
    //动态添加路由
    hasNewRoutes = addRoutes(menu)
  }

  //设置页面标题
  //console.log(to);
  let title = (to.meta.title ? to.meta.title : '网站')
  document.title = title

  //手动指定路由
  hasNewRoutes ? next(to.fullPath) : next()
})

//全局后置守卫
router.afterEach((to, from) => {
  hideFullLoading()
})